package com.genersoft.iot.vmp.utils;

/**
 * @author ：mengfanlu
 * @date ：Created in 2022/1/21 17:37
 * @description：...
 * @modified By：
 * @version: ${1.0.0}
 */
public class RtpPacket {

    private final byte version = 2;

    private final byte padding = 0;

    private final byte extension = 0;

    private final byte csrcCount = 0;

    private final byte marker = 1;

    private byte playloadType = 0;

    private int sequenceNumber = 0;

    private long timestamp = 0;

    private long ssrc = 0;


    public RtpPacket(long ssrcVal) {

        ssrc = ssrcVal;
    }

    public byte[] packetG711a(byte[] audioData, int audioLen, int headLength) {
        byte[] payload = new byte[headLength + audioLen];
        playloadType = (byte)RtpPayloadType.RTP_PAYLOAD_TYPE_PCMA;
        sequenceNumber++;
        timestamp += audioLen;

        if (headLength == 14){
            int length = payload.length - 2;
            payload[0] = (byte) ((length & 0xff00) >> 8);
            payload[1] = (byte) (length & 0x00ff);
            payload[2] = (byte)( (version << 6) +  (padding << 5) + (extension << 4) + csrcCount );
            payload[3] = (byte)( (marker << 7) + playloadType );
            payload[4] = (byte)( sequenceNumber / (0xff + 1) );
            payload[5] = (byte)( sequenceNumber % (0xff + 1) );
            payload[6] = (byte)( ( timestamp / (0xffff + 1) ) / (0xff + 1) );
            payload[7] = (byte)( ( timestamp / (0xffff + 1) ) % (0xff + 1) );
            payload[8] = (byte)( ( timestamp % (0xffff + 1) ) / (0xff + 1) );
            payload[9] = (byte)( ( timestamp % (0xffff + 1) ) % (0xff + 1) );
            payload[10] = (byte)( ( ssrc / (0xffff + 1) ) / (0xff + 1) );
            payload[11] = (byte)( ( ssrc / (0xffff + 1) ) % (0xff + 1) );
            payload[12] = (byte)( ( ssrc % (0xffff + 1) ) / (0xff + 1) );
            payload[13] = (byte)( ( ssrc % (0xffff + 1) ) % (0xff + 1) );
        }else {
            payload[0] = (byte)( (version << 6) +  (padding << 5) + (extension << 4) + csrcCount);
            payload[1] = (byte)( (marker << 7) + playloadType);
            payload[2] = (byte)( sequenceNumber / (0xff + 1) );
            payload[3] = (byte)( sequenceNumber % (0xff + 1) );
            payload[4] = (byte)( ( timestamp / (0xffff + 1) ) / (0xff + 1) );
            payload[5] = (byte)( ( timestamp / (0xffff + 1) ) % (0xff + 1) );
            payload[6] = (byte)( ( timestamp % (0xffff + 1) ) / (0xff + 1) );
            payload[7] = (byte)( ( timestamp % (0xffff + 1) ) % (0xff + 1) );
            payload[8] = (byte)( ( ssrc / (0xffff + 1) ) / (0xff + 1) );
            payload[9] = (byte)( ( ssrc / (0xffff + 1) ) % (0xff + 1) );
            payload[10] = (byte)( ( ssrc % (0xffff + 1) ) / (0xff + 1) );
            payload[11] = (byte)( ( ssrc % (0xffff + 1) ) % (0xff + 1) );
        }

        System.arraycopy(audioData, 0, payload, headLength, audioLen);
        return payload;
    }
}
